/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.zprofilefrontend.model;

import com.vng.zing.calc.thrift.GENDER;
import com.vng.zing.calc.thrift.Profile;
import com.vng.zing.calc.thrift.ROLE;
import com.vng.zing.calc.thrift.SOURCE;
import com.vng.zing.calc.thrift.STATUS;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

/**
 *
 * @author namhh
 */
public class FacebookApi {

    private static FacebookApi _INSTANCE;
    HttpClient httpclient;

    private FacebookApi() {
        httpclient = new DefaultHttpClient();
    }

    public static FacebookApi getInstance() {
        return (null == _INSTANCE) ? _INSTANCE = new FacebookApi() : _INSTANCE;
    }

    public Map<String, Object> getProfileFrom(String code) {
        try {
            Map<String, Object> ret = getFacebookAccessToken(code);
            String accessToken = (String) ret.get("token");
            String jsonString = getProfile(accessToken);
            Profile profile = mapToProfile(jsonString);
            ret.put("profile", profile);
            return ret;
        } catch (Exception ex) {
            return null;
        }
    }

    private Map<String, Object> getFacebookAccessToken(String faceCode) {
        Map<String, Object> ret = new HashMap<String, Object>();
        if (faceCode != null && !"".equals(faceCode)) {
            String appId = "236551069873118";
            String redirectUrl = "http://localhost:8000/fblogin";
            String faceAppSecret = "7c4779e90518531090b5931db7c83bbf";
            String newUrl = "https://graph.facebook.com/oauth/access_token?client_id="
                    + appId + "&redirect_uri=" + redirectUrl + "&client_secret="
                    + faceAppSecret + "&code=" + faceCode;

            try {
                httpclient = new DefaultHttpClient();
                HttpGet httpget = new HttpGet(newUrl);
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                String token = httpclient.execute(httpget, responseHandler);
                token = token.substring(token.indexOf("=") + 1);
                Long expires = Long.valueOf(token.substring(token.lastIndexOf("=") + 1))/1000;
                token = token.substring(0, token.indexOf("&expires"));
                ret.put("token", token);
                ret.put("exp", expires.intValue());
                return ret;
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                httpclient.getConnectionManager().shutdown();
            }
        }
        return null;
    }

    private String getProfile(String token) {
        String profile = null;
        if (token != null && !"".equals(token)) {
            String newUrl = "https://graph.facebook.com/me?access_token=" + token;
            httpclient = new DefaultHttpClient();
            try {
                HttpGet httpget = new HttpGet(newUrl);
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                profile = httpclient.execute(httpget, responseHandler);

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                httpclient.getConnectionManager().shutdown();
            }
        }
        return profile;
    }

    private static Profile mapToProfile(String jsonData) {
        try {
            JSONParser parser = new JSONParser();
            Object obj = parser.parse(jsonData);
            JSONObject jsonObject = (JSONObject) obj;
            Profile profile = new Profile();
            profile.setEmail((String) jsonObject.get("email"));
            profile.setUsername(String.format("%s_%s", SOURCE.FB, jsonObject.get("id")));
            profile.setPassword("");
            String gender = ((String) jsonObject.get("gender")).toUpperCase();
            profile.setGender(GENDER.valueOf(gender));
            profile.setDisplayName((String) jsonObject.get("name"));
            profile.setRole(ROLE.USER);
            profile.setSource(SOURCE.FB);
            profile.setUID((String) jsonObject.get("id"));
            profile.setStatus(STATUS.PENDING);
            return profile;
        } catch (ParseException ex) {
        }
        return null;
    }

    public void logOut(String token) {
        if (token != null && !"".equals(token)) {
            String newUrl = "https://www.facebook.com/logout.php?&access_token=" + token;
            try {
                httpclient = new DefaultHttpClient();
                HttpGet httpget = new HttpGet(newUrl);
                httpclient.execute(httpget);

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                httpclient.getConnectionManager().shutdown();
            }
        }

    }

}
